package com.admin.cartAndOrder.service.impl;

import com.admin.cartAndOrder.pojo.MobileEndCart;
import com.admin.cartAndOrder.pojo.MobileEndOrder;
import com.admin.cartAndOrder.mapper.MobileEndOrderMapper;
import com.admin.cartAndOrder.pojo.Order;
import com.admin.cartAndOrder.pojo.OrderInfo;
import com.admin.cartAndOrder.service.MobileEndCartService;
import com.admin.cartAndOrder.service.MobileEndOrderService;
import com.admin.discountService.mapper.MobileEndDiscountMapper;
import com.admin.discountService.pojo.MobileEndDiscount;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * <p>
 * 订单表 服务实现类
 * </p>
 *
 * @author liu-xiang
 * @since 2022-12-14
 */
@Service
public class MobileEndOrderServiceImpl extends ServiceImpl<MobileEndOrderMapper, MobileEndOrder> implements MobileEndOrderService {

    @Autowired
    private MobileEndOrderMapper orderMapper;

    @Autowired
    private MobileEndCartService mobileEndCartService;

    @Autowired
    private MobileEndDiscountMapper mobileEndDiscountMapper;
    public MobileEndOrderServiceImpl()
    {
    }


    /**
     *创建要保存的订单对象
     * 根据穿入的orderinfo生成存到数据库的订单对象
     * 值得注意的是要设置默认的订单状态为已结算
     * 设置所使用到的优惠券状态为已使用
     * 还要将相关购物车项状态设置为以下单
     */
    public MobileEndOrder createOrder(OrderInfo orderInfo)
    {
        MobileEndOrder mobileEndOrder = new MobileEndOrder();
        mobileEndOrder.setAddress(orderInfo.getAddress());
        mobileEndOrder.setName(orderInfo.getName());
        mobileEndOrder.setTel(orderInfo.getTel());
        mobileEndOrder.setUserNum(orderInfo.getUserNum());
        mobileEndOrder.setCreateTime(new Date());
        mobileEndOrder.setCartItem(parseTool1(orderInfo.getCartIds()));
        mobileEndOrder.setStatus(Integer.valueOf("1"));//设置默认订单状态
        mobileEndOrder.setOrderid(createOrderId(orderInfo.getUserNum()));
        mobileEndOrder.setTotalPrice(orderInfo.getTotalPrice());
        mobileEndOrder.setRealPrice(orderInfo.getRealPrice());
        mobileEndOrder.setDiscountId(orderInfo.getDiscountId());
        MobileEndDiscount discount = mobileEndDiscountMapper.selectById(orderInfo.getDiscountId());
        //将优惠券状态设置为已使用
        if (discount!=null) {
            discount.setState(1);
        }
        mobileEndDiscountMapper.updateById(discount);//将状态修改保存到数据库
        List<MobileEndCart> mobileEndCarts = mobileEndCartService.listByIds(Arrays.asList(orderInfo.getCartIds()));//获取订单项将状态设置为已下单
        for(MobileEndCart m:mobileEndCarts){
            m.setOrderStatus(1);//修改状态为以下单项
            mobileEndCartService.save(m);//储存到数据库
        }
        return mobileEndOrder;
    }

    /**
     * 根据id获取订单信息
     * 封装带有购物详细信息以及优惠券信息的order对象返回前端
     * @param orderId
     * @return
     */
    public Order getOrderByOrderId(String orderId) throws RuntimeException
    {
        Order order = new Order();
        MobileEndOrder mobileEndOrder = orderMapper.selectById(orderId);
        order.setUserNum(mobileEndOrder.getUserNum());
        order.setAddress(mobileEndOrder.getAddress());
        order.setName(mobileEndOrder.getName());
        order.setTel(mobileEndOrder.getTel());
        order.setStatus(mobileEndOrder.getStatus());
        order.setCreateTime(mobileEndOrder.getCreateTime());
        order.setTotalPrice(mobileEndOrder.getTotalPrice());
        order.setRealPrice(mobileEndOrder.getRealPrice());
        String cartItem = mobileEndOrder.getCartItem();
        List<Integer> cartIds = parseTool2(cartItem);
        System.out.println(cartIds);
        ArrayList<HashMap<String,Object>> cartInfos = new ArrayList<>();
        MobileEndCart mobileEndCart;
        for(Iterator<Integer> iterator = cartIds.iterator(); iterator.hasNext();)//解析所涉及到的购物项id并塞入到order对象
        {
            Integer cartId = (Integer)iterator.next();
            HashMap<String,Object> map = new HashMap<>();
            mobileEndCart = mobileEndCartService.getById(cartId);
            if(mobileEndCart!=null) {
                map.put("cart", mobileEndCart);
                map.put("count", mobileEndCart.getCount());
            }
            cartInfos.add(map);
        }

        MobileEndDiscount discount = mobileEndDiscountMapper.selectById(mobileEndOrder.getDiscountId());
        order.setCartInfos(cartInfos);//设置购物项信息
        order.setDiscount(discount);//设置优惠券信息
        return order;
    }

    /**
     * 查看所有订单
     * @param userNum
     * @return
     */
    public List getAllOrders(String userNum)
    {
        ArrayList orders = new ArrayList();
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("userNum", userNum);
        List mobileEndOrders = orderMapper.selectList(wrapper);
        Order order;
        for(Iterator iterator = mobileEndOrders.iterator(); iterator.hasNext(); orders.add(order))
        {
            MobileEndOrder m = (MobileEndOrder)iterator.next();
            order = getOrderByOrderId(m.getOrderid());
        }

        return orders;
    }

    /**
     * 根据订单的id和根据所需要设置的订单状态设置状态
     * @param orderId
     * @param status
     * @return
     */
    public Boolean updateStatus(String orderId, Integer status)
    {
        MobileEndOrder mobileEndOrder = orderMapper.selectById(orderId);
        mobileEndOrder.setStatus(status);
        return Boolean.valueOf(orderMapper.updateById(mobileEndOrder) != 0);
    }

    /**
     * 根据传入的下单的购物项id进行解析为购物想项号信息字符串
     * @param cartIds
     * @return
     */
    private String parseTool1(Integer cartIds[])
    {
        StringBuilder builder = new StringBuilder();
        for(int i = 0; i < cartIds.length; i++)
        {
            builder.append(Integer.toString(cartIds[i].intValue()));
            if(i != cartIds.length - 1)
                builder.append("-");
        }

        return builder.toString();
    }

    /**
     * 根据用户编号生成订单id
     * @param userNum
     * @return
     */
    private String createOrderId(String userNum)
    {
        String s = UUID.randomUUID().toString();
        s.replace("-", "");
        s = (new StringBuilder()).append(s).append(userNum).toString();
        return s;
    }

    /**
     * 解析订单购物项编号解析成购物项id集合
     * @param cartItem
     * @return
     */
    private List<Integer> parseTool2(String cartItem)
    {
        ArrayList<Integer> carts = new ArrayList<>();
        String strings[] = cartItem.split("-");
        String as[] = strings;
        int i = as.length;
        for(int j = 0; j < i; j++)
        {
            String str = as[j];
            carts.add(Integer.valueOf(Integer.parseInt(str)));
        }

        return carts;
    }

}
